import React, { useEffect, useState } from 'react';
import moment from 'moment'
import {
  Table, Checkbox, Row, Modal, Form, Input, Col, message, InputNumber, Select, Button, TimePicker, DatePicker,
} from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import RenderButtom from '@/components/RenderButton';
import SearchBox from '@/components/SearchBox'
import {
  handleSupplier,
} from '@/services/goodCenter/invoicing';
import { connect } from 'dva';
import { formItemLayout } from '@/utils/utils';

const hasSearchBtn = JSON.parse(localStorage.getItem('hasSearchBtn'))
const { Option } = Select
const { MonthPicker } = DatePicker

const statusLists = ['', '空闲/正常', '已预定', '使用中', '维修中']
const arrtion = ['否', '是']
const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    align: 'center',
    key: 'index',
  },
  {
    title: '台房名称',
    align: 'center',
    key: 'name',
  },
  {
    title: '楼层',
    align: 'center',
    key: 'floorName',
  },
  {
    title: '类型',
    align: 'center',
    key: 'typeName',
  },
  {
    title: '保底消费',
    align: 'center',
    key: 'limitAmount',
  },
  {
    title: '状态',
    align: 'center',
    key: 'status',
    render: p => (<span>{ statusLists[p.status] }</span>),
  },
  {
    title: '是否开启预定',
    align: 'center',
    key: 'isReservation',
    render: p => (<span>{ arrtion[p.isReservation] }</span>),
  },
  {
    title: '是否开启排班',
    align: 'center',
    key: 'isScheduling',
    render: p => (<span>{ arrtion[p.isScheduling] }</span>),
  },
  {
    title: '创建时间',
    align: 'center',
    key: 'createTime',
  },
  {
    title: '二维码',
    align: 'center',
    key: 'accountQrcode',
    render: p => (<Button type="ghost" onClick={() => window.open(p.accountQrcode)}>下载二维码</Button>),
  },
];
const statusList = [
  {
    label: '空闲/正常',
    value: '1',
  },
  {
    label: '已预定',
    value: '2',
  },
  {
    label: '使用中',
    value: '3',
  },
  {
    label: '维修中',
    value: '4',
  },
]
const roomSchedule = props => {
  const { getFieldDecorator } = props.form;
  const [data, setColData] = useState([]);
  const [record, setRecord] = useState([]);
  const [floors, setfloors] = useState([]);
  const [month, setmonth] = useState(null);
  const [roomtypes, setroomtypes] = useState([]);
  const [staffList, setStaffList] = useState([]);
  const [mondata, setmondata] = useState([]);
  const [endTime, setendTime] = useState(null);
  const [startTime, setstartTime] = useState(null);
  const [checkhour, setcheckhour] = useState([]);
  const [checkmin, setcheckmin] = useState([]);
  const [roomname, setroomname] = useState('');
  const [listQuery, setListQuery] = useState({
    pageNo: 1,
    pageSize: 10,
  });
  const [info, setInfo] = useState({});
  // 分配\新增角色模态框
  const [isShow, setState] = useState(false);
  const [confirmLoading, setconfirmLoading] = useState(false);

  // 列表
  const getList = async params => {
    const r = await handleSupplier(params, 'GET');
    if (r.data && r.data.data) {
      setColData(r.data.data);
    }
  };
  const checkmonth = m => {
    const tDate = new Date()
    let year = tDate.getFullYear()
    let month = tDate.getMonth() + 1
    if (m) {
      year = m.split('-')[0]
      month = m.split('-')[1]
    }
    const stratDate = new Date(year, month - 1, 1)
    const endData = new Date(year, month, 1);
    const days = (endData - stratDate) / (1000 * 60 * 60 * 24);
    return days
  }
  const renderMondata = async t => {
    const monday = await checkmonth(t)
    const anewArr = []
    for (let i = 0; i < monday; i++) {
      anewArr.push({
        checked: false,
        a: '',
        waiterStaffName: '',
      })
    }
    setmondata(anewArr)
  }
  useEffect(() => {
    getList(listQuery);
    renderMondata()
  }, []);

  // 查询
  const searchOneBtn = async params => {
    getList(params);
  };
  // 新增/修改 模态框
  const handleStatus = () => {
    console.log('批量操作')
    let stas = false
    for (let i in mondata) {
      if (mondata[i].checked) {
        stas = true
        break
      }
    }
    if (stas) {
      setState(true)
    } else {
      message.warning('请勾选一条数据！')
    }
  };
  // 查询表单
  const getFields = () => (
    <Col span={18}>
      <Col span={8}>
        <Form.Item label="市别名称">
          <Select value={listQuery.periodId} placeholder="选择市别名称" onChange={v => { setListQuery({ ...listQuery, periodId: v }) }}>
            {roomtypes.map(r => <Option key={r.id}>{r.label}</Option>)}
          </Select>
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="选择月份">
          <MonthPicker value={month} onChange={(v, t) => {
            setInfo({ ...listQuery, month: t })
            setmonth(v)
            renderMondata(t)
          }} placeholder="选择月份" />
        </Form.Item>
      </Col>
    </Col>
  );
  // 查询表单逻辑
  const handleSearch = e => {
    e.preventDefault()
    searchOneBtn(listQuery);
  };

  // 表单提交
  const handleSubmit = e => {
    e.preventDefault();
    props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        // let med = 'POST'
        // if (values.id) {
        //   med = 'PUT'
        // }
        // setconfirmLoading(true)
        // handleSupplier({ storeBusiness: values }, med).then(() => {
        //   getList(listQuery)
        //   setState(!isShow);
        //   setconfirmLoading(false)
        // }).catch(() => {
        //   setconfirmLoading(false)
        // })
      }
    });
  };
  // 清空查询条件
  const handleReset = () => {
    const aobj = {
      pageNo: 1,
      pageSize: 10,
    }
    setListQuery(aobj)
    getList(aobj)
  };
  const checkAll = () => {
    mondata.forEach(v => {
      v.checked = true
    })
    setmondata([...mondata])
  }
  const cancelAll = () => {
    mondata.forEach(v => {
      v.checked = false
    })
    setmondata([...mondata])
  }
  // 按钮逻辑
  const handleBtn = type => {
    switch (type) {
      // 全选
      case 94:
        return checkAll();
      // 取消选中
      case 95:
        return cancelAll();
      // 批量操作
      case 96:
        return handleStatus();
      default:
        return ''
    }
  };
  const colMondata = i => (
    <Col xs={12} sm={8} md={6} lg={4} xl={3} key={i}>
      <div className="adaybox">
        <div className="aday-header">
          <Checkbox
            checked={mondata[i].checked}
            onChange={e => {
              mondata[i].checked = e.target.checked
              setmondata([...mondata])
            }}
          >
            <span className="aday-text">{i + 1}号</span>
          </Checkbox>
        </div>
        <div className="aday-body">
          <div className="myellips">分销人：{mondata[i].a}</div>
          <div className="myellips">员工：{mondata[i].waiterStaffName}</div>
          <Button className="marginT10" type="primary" size="small" onClick={() => { setState(true) }}>操作</Button>
        </div>
      </div>
    </Col>
  )
  return (
    <PageHeaderWrapper>
      <p>当前包房：{ roomname }</p>
      {/* 查询条件 */}
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      {/* 新增/修改 */}
      <Row gutter={15}>
        {mondata.map((v, i) => (
          colMondata(i)
        ))}
      </Row>
      <Modal
        title="排班及提成方案设置"
        visible={isShow}
        confirmLoading={confirmLoading}
        onOk={handleSubmit.bind(this)}
        onCancel={() => setState(false)}
        destroyOnClose
      >
        <Form {...formItemLayout}>
          <Form.Item label="分销人">
            <span>分销人由系统设定</span>
          </Form.Item>
          <Form.Item label="指派专属人员">
            {getFieldDecorator('waiterStaffId', {
              initialValue: info.waiterStaffId,
              rules: [
                {
                  required: true,
                  message: '请选择专属人员',
                },
              ],
            })(<Select placeholder="请选择专属人员">
              {staffList.map(r => <Option key={r.id}>{r.name}</Option>)}
            </Select>)}
          </Form.Item>
          <Form.Item label="房费总提成">
            {getFieldDecorator('roomDistributionRate', {
              initialValue: info.roomDistributionRate,
              rules: [
                {
                  required: true,
                  message: '请输入房费总提成',
                },
              ],
            })(<Input placeholder="以实际支付金额为基数" />)}
          </Form.Item>
          <Form.Item label="房费提成占比">
            {getFieldDecorator('staffRoomDistributionRate', {
              initialValue: info.staffRoomDistributionRate,
              rules: [
                {
                  required: true,
                  message: '请输入房费提成占比',
                },
              ],
            })(<Input placeholder="专属人员占总提成比例" />)}
          </Form.Item>
          <Form.Item label="房费提成占比">
            {getFieldDecorator('data1', {
              initialValue: info.data1,
              rules: [
                {
                  required: true,
                  message: '请输入房费提成占比',
                },
              ],
            })(<Input placeholder="分销人员占总提成比例" />)}
          </Form.Item>
          <Form.Item label="消费提成占比">
            {getFieldDecorator('staffGoodsDistributionRate', {
              initialValue: info.staffGoodsDistributionRate,
              rules: [
                {
                  required: true,
                  message: '请输入消费提成占比',
                },
              ],
            })(<Input placeholder="专属人员占总提成比例" />)}
          </Form.Item>
          <Form.Item label="消费提成占比">
            {getFieldDecorator('data2', {
              initialValue: info.data2,
              rules: [
                {
                  required: true,
                  message: '请输入消费提成占比',
                },
              ],
            })(<Input placeholder="分销人员占总提成比例" />)}
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default connect(({ role, global }) => ({
  role,
  hasSearchBtn: global.hasSearchBtn,
}))(Form.create()(roomSchedule));
